import React from "react";
import Button from "antd/lib/button";
import Col from "antd/lib/col";
import Divider from "antd/lib/divider";
import Row from "antd/lib/row";
import Menu from "antd/lib/menu";
import Dropdown from "antd/lib/dropdown";
import Table from "antd/lib/table";
import Select from 'antd/lib/select';
import ConfigProvider from "antd/lib/config-provider";
import Layout from "antd/lib/layout";
import Modal from "antd/lib/modal";
import AutoComplete from "antd/lib/auto-complete";
import zhCN from 'antd/es/locale/zh_CN';
import Payment from "@/services/payment";
import { currentUser } from "@/services/auth";
import notification from "@/services/notification";
import { get } from "lodash";
import moment from "moment";
import Workflow from "@/services/workflow";
import QueryShowField from "@/services/queryshowfield";
import CreateQueryShowFieldDialog from "@/components/enums/QueryShowFieldDialog";
import { AppstoreFilled, DownOutlined, UpOutlined } from "@ant-design/icons";
import CheckDialog from "@/components/workflow/CheckDialog";
import DatePicker from "antd/lib/date-picker";
import locale from 'antd/es/date-picker/locale/zh_CN';


const { confirm } = Modal;
const getRowClassName = (record, index) => {
  let className = '';
  if (index % 2 === 0) className = "oddRow";
  return className
}

export default class PaymentList extends React.Component {
  state = {
    page: 1,
    pagesize: localStorage.getItem("paymentlistpagesize") ? (localStorage.getItem("paymentlistpagesize") !== undefined ? Number(localStorage.getItem("paymentlistpagesize")) : 20) : 20,
    total: 1,
    order: 1,
    loading: false,
    code: localStorage.getItem("paymentlistcode") ? (localStorage.getItem("paymentlistcode") !== undefined ? localStorage.getItem("paymentlistcode") : '') : '',
    name: localStorage.getItem("paymentlistname") ? (localStorage.getItem("paymentlistname") !== undefined ? localStorage.getItem("paymentlistname") : '') : '',
    status: localStorage.getItem("paymentliststatus") ? (localStorage.getItem("paymentliststatus") !== undefined ? localStorage.getItem("paymentliststatus") : '') : '',
    bill_date: [moment().startOf('year'),moment()],
    userid: currentUser.id,
    data: [],
    statusdata: [{ id: "", name: "全部" }, { id: "0", name: "草稿" }, { id: "1", name: "审核中" }, { id: "0", name: "已审核" }],
    queryshowfielddata: [],
    showall: false,
  };
  componentWillMount() {
    this.fieldsshowload();
    let param = {
      page: this.state.page,
      pagesize: this.state.pagesize,
      code: this.state.code,
      name: this.state.name,
      status: this.state.status,
      userid: this.state.userid,
      paytype: this.props.paytype,
      id: 0,
      datadown: false,
    }
    this.seldata(param);
  }
  fieldsshowload = () => {
    if (this.props.paytype === 0) {
      QueryShowField.getbycode("paymentoutlist").then(data => {
        this.setState({
          queryshowfielddata: data,
        });
      });
    } else {
      QueryShowField.getbycode("paymentinlist").then(data => {
        this.setState({
          queryshowfielddata: data,
        });
      });
    }
  }
  handlefieldshow = () => {
    CreateQueryShowFieldDialog.showModal({ queryshowfield: this.state.queryshowfielddata })
      .onClose((result = {}) => {
        if (result.success) {
          this.fieldsshowload();
        }
      }).onDismiss(() => {
      });
  }
  isEmptyobj = (str) => {
    if (str === '' || str === null || str === 'null' || str === undefined || str === 'undefined') {
      return true;
    } else {
      return false;
    }
  }
  seldata = (params = {}) => {
    if (!this.isEmptyobj(this.state.bill_date)) {
      if (this.state.bill_date.length === 2) {
        params.begindate = this.state.bill_date[0].format('YYYY-MM-DD');
        params.enddate = this.state.bill_date[1].format('YYYY-MM-DD');
      }
    }
    if (!currentUser.hasPermission("super_admin")) {
      params.userid = currentUser.id;
    }
    if (params.datadown) {
      if (this.state.data.length < 1) {
        notification.error("没有要导出的数据");
        return;
      }
      let AjaxUrl = 'api/payment/list';
      fetch(AjaxUrl, {
        method: 'POST',
        body: window.JSON.stringify(params),
        credentials: 'include',
        headers: new Headers({
          'Content-Type': 'application/json'
        })
      }).then((response) => {
        response.blob().then(blob => {
          const aLink = document.createElement('a');
          document.body.appendChild(aLink);
          aLink.style.display = 'none';
          const objectUrl = window.URL.createObjectURL(blob);
          aLink.href = objectUrl;
          aLink.download = '款项信息.xlsx';
          aLink.click();
          document.body.removeChild(aLink);
        });
      }).catch((error) => {
        window.console.log(error);
      });
    }
    else {
      this.setState({ loading: true });
      Payment.getlist(params).then(data => {
        this.setState({
          loading: false,
          data: data.data,
          page: params.page,
          pagesize: params.pagesize,
          total: data.total,
          field: params.field,
          order: params.order,
        });
      });
    }
  };

  handlesel = (index) => {
    let datadown = false;
    if (index === 2) {
      datadown = true;
    }
    let param = {
      page: 1,
      pagesize: this.state.pagesize,
      code: this.state.code,
      name: this.state.name,
      status: this.state.status,
      userid: this.state.userid,
      paytype: this.props.paytype,
      id: 0,
      datadown: datadown,
    }
    this.seldata(param);
  };
  handleDelete = record => {
    if (record.blnisinactive) {
      notification.error("只有在草稿状态可以删除，删除失败！");
      return;
    }
    if (!currentUser.hasPermission("admin")) {
      notification.error("只有管理员可以删除，删除失败！");
      return;
    }
    confirm({
      title: '确定删除款项记录?',
      content: record.code,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        Payment.delete(record).then(() => {
          notification.success("删除成功.");
          let param = {
            page: 1,
            pagesize: this.state.pagesize,
            code: this.state.code,
            name: this.state.name,
            status: this.state.status,
            userid: this.state.userid,
            id: 0,
            datadown: false,
            paytype: this.props.paytype,
          }
          this.seldata(param);
        }).catch(error => {
          notification.error(get(error, "response.data.message", "删除失败."));
        });
      },
    });
  };
  handleTableChange = (pagination, filters, sorter) => {
    localStorage.setItem("paymentlistpagesize", pagination.pageSize);
    let field = sorter.field;
    let order = 0;
    if (sorter.order === "descend") {
      order = 1;
    }
    let param = {
      field: field,
      order: order,
      page: pagination.current,
      pagesize: this.state.pagesize,
      code: this.state.code,
      name: this.state.name,
      status: this.state.status,
      userid: this.state.userid,
      id: 0,
      datadown: false,
      paytype: this.props.paytype,
    }
    this.seldata(param);
  };
  handleCheck = (record) => {
    if (!currentUser.isAudit) {
      notification.error("没有权限.");
      return;
    }

    const item = {
      bill: "payment",
      billtype: this.props.paytype,
      billid: record.paymentid,
      next_type: 1,
      message: '<div>同意</div>',
      userid: currentUser.id,
      billdate: moment().format('YYYY-MM-DD'),
      orgunitid: record.orgunitid,
      status: record.status,
    }
    let param = {
      page: 1,
      pagesize: this.state.pagesize,
      code: this.state.code,
      name: this.state.name,
      status: this.state.status,
      userid: this.state.userid,
      id: 0,
      datadown: false,
      paytype: this.props.paytype,
    }
    if (record.status === 0) {
      Workflow.check(item).then(data => {
        if (data[0].flag === 0) {
          notification.success(data[0].message);
          this.seldata(param);
        } else {
          notification.error(data[0].message);
        }
      })
        .catch(error => {
          notification.error(error.message, error.detailedMessage);
        });
    } else {
      CheckDialog.showModal({ bill_check: item })
        .onClose((result = {}) => {
          if (result.success) {
            this.seldata(param);
          }
        }).onDismiss(() => {
        });
    }
  }
  onDragEnter = info => {
    window.console.log(info);
  };
  handleclear = () => {
    this.setState({
      code: "",
      name: "",
      status: "",
      bill_date: [moment().startOf('year'),moment()],
      userid: currentUser.id,
    });
    localStorage.setItem("paymentlistcode", "");
    localStorage.setItem("paymentlistname", "");
    localStorage.setItem("paymentliststatus", "");
  }
  render() {
    const paginationProps = {
      showSizeChanger: true,
      total: this.state.total, // 数据总数
      pageSize: parseInt(this.state.pagesize), // 每页条数
      current: parseInt(this.state.page), // 当前页码
      pageSizeOptions: ["10", "20", "30", "100"],
      showTotal: ((total) => {
        return `共 ${total} 条`;
      }),
    };
    let listcolumns = [];
    if (this.state.queryshowfielddata.fieldsshow !== undefined) {
      (this.state.queryshowfielddata.fieldsshow || []).map(item => {
        let items = this.state.queryshowfielddata.fieldsall.filter((p) => {
          return p.key === item;
        });
        if (items.length > 0) {
          listcolumns.push({
            title: items[0].title,
            dataIndex: item,
            key: item,
            sorter: (a, b) => a[item] > b[item] ? 1 : -1
          })
        }
        return item;
      }
      );
    }

    listcolumns.push({
      title: '操作',
      key: 'action',
      render: (record) => (
        <span>
          <Dropdown
            trigger={["click"]}
            overlay={
              <Menu>
                {(record.type === 0) && (<Menu.Item key="change-item-in">
                  <a href={`/payment/outnew/${record.paymentid}/0`} >查看</a>
                </Menu.Item>)}
                {(record.type === 1) && (<Menu.Item key="change-item-in">
                  <a href={`/payment/innew/${record.paymentid}/0`} >查看</a>
                </Menu.Item>)}
                <Menu.Divider />
                <Menu.Item key="change-item-out">
                  <a className="clickable" onClick={() => this.handleCheck(record)}>{record.status === 0 ? "审核" : (record.status === 1 ? "审核中" : "已审核")}</a>
                </Menu.Item>
                <Menu.Divider />
              </Menu>
            }>
            <Button type="primary" data-test="CreateButton" size="small">
              ...
            </Button>
          </Dropdown>
        </span>
      ),
    });
    return (
      <ConfigProvider locale={zhCN}>
        <Layout>
          <Layout style={{ padding: '0 24px 24px' }}>
            {this.state.showall && (<><Row style={{ marginBottom: 5 }}>
              <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
                单据状态:</div></Col>
              <Col span={6}>
                <Select style={{ width: "100%" }}
                  showSearch
                  allowClear
                  optionFilterProp="children"
                  value={this.state.status}
                  onChange={value => this.setState({ status: value })} >
                  {(this.state.statusdata || []).map(item => (
                    <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
                  ))}
                </Select>
              </Col>
              <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
                日期:</div></Col>
              <Col span={6}>
                <DatePicker.RangePicker
                  locale={locale}
                  style={{ width: "100%" }}
                  value={this.state.bill_date}
                  onChange={value => {
                    this.setState({
                      bill_date: value,
                    });
                  }}
                  autoFocus
                />
              </Col>
              {currentUser.hasPermission("super_admin") && (<><Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
                录入人:</div></Col>
                <Col span={6}>
                  <Select style={{ width: "100%" }}
                    showSearch
                    allowClear
                    optionFilterProp="children"
                    value={this.state.userid}
                    onChange={value => {
                      this.setState({ userid: value });
                    }}>
                    {(this.state.employeeuserdata || []).map(item => (
                      <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
                    ))}
                  </Select>
                </Col></>)}

            </Row></>)}

            <Row style={{ marginBottom: 5 }}>
              <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
                人员编码:</div></Col>
              <Col span={6}>
                <AutoComplete
                  style={{ width: "100%" }}
                  value={this.state.code}
                  onChange={value => {
                    localStorage.setItem("paymentlistcode", value);
                    this.setState({ code: value });
                  }}
                  placeholder="人员编码"
                  filterOption={(inputValue, option) =>
                    option.value.indexOf(inputValue) !== -1}>
                </AutoComplete>
              </Col>
              <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
                人员名称:</div></Col>
              <Col span={6}>
                <AutoComplete
                  style={{ width: "100%" }}
                  value={this.state.name}
                  onChange={value => {
                    localStorage.setItem("paymentlistname", value);
                    this.setState({ name: value });
                  }}
                  placeholder="人员名称"
                  filterOption={(inputValue, option) =>
                    option.value.indexOf(inputValue) !== -1}>
                </AutoComplete>
              </Col>
              <Col span={8}>
                <Divider type="vertical" />
                <Button type="primary" onClick={() => this.handlesel(1)} >
                  <i className="fa fa-search m-r-5" />
                  查询
                </Button>
                <Divider type="vertical" />
                <Button onClick={() => this.handleclear()} >
                  清空
                </Button>
                <Divider type="vertical" />
                <Button onClick={() => { this.setState({ showall: !this.state.showall }); }} >
                  {this.state.showall && (<UpOutlined />)}
                  {!this.state.showall && (<DownOutlined />)}
                  {this.state.showall ? '默认' : '更多'}
                </Button>
              </Col>
            </Row>
            <Row style={{ marginBottom: 5 }}>
              <Col span={10}>
                <Button type="primary" >
                  <i className="fa fa-plus m-r-5" />
                  {this.props.paytype === 0 && (
                    <a href="payment/outnew/0" style={{ color: "white" }}>付款录入</a>)}
                  {this.props.paytype === 1 && (
                    <a href="payment/innew/0" style={{ color: "white" }}>收款录入</a>)}
                </Button>
                <Divider type="vertical" />
                <Dropdown
                  trigger={["click"]}
                  overlay={
                    <Menu>
                      {currentUser.hasPermission("ryexcelout") && (
                        <Menu.Item key="change-item-out">
                          <a onMouseUp={() => this.handlesel(2)}>EXCEL导出</a>
                        </Menu.Item>)}
                      {currentUser.hasPermission("ryexcelout") && (<Menu.Divider />)}

                      {currentUser.hasPermission("fieldshow") && (
                        <Menu.Item key="delete-item">
                          <a onMouseUp={() => this.handlefieldshow()}>显示隐藏列</a>
                        </Menu.Item>
                      )}
                    </Menu>
                  }>
                  <Button type="primary" style={{ margin: "10px" }} data-test="CreateButton" >
                    <AppstoreFilled />更多功能
                  </Button>
                </Dropdown>
              </Col>
            </Row>
            <div>
              <Table rowKey='id'
                rowClassName={(record, index) => getRowClassName(record, index)}
                columns={listcolumns}
                scroll={{ x: 'max-content' }}
                dataSource={this.state.data}
                pagination={paginationProps}
                loading={this.state.loading}
                onChange={this.handleTableChange}
              />
            </div>
          </Layout>
        </Layout>
      </ConfigProvider>
    );
  }
}